import React, { createContext, useContext, ReactNode } from "react";
import useAuth from "../hooks/useAuth";

export interface User {
  id: string;
  name: string;
  role: "admin" | "teacher" | "student";
  email: string;
  phone?: string;
  avatar?: string;
  permissions: string[];
  bio?: string;
  // 教师专有字段
  department?: string;
  title?: string;
  subject?: string;
  teacherNo?: string;
  // 学生专有字段
  studentId?: string;
  major?: string;
  className?: string;
  grade?: string;
  // 兼容AuthContext
  type?: string;
  classId?: number;
  gender?: number;
  settings?: {
    theme?: "light" | "dark";
    fontSize?: "small" | "medium" | "large";
    notifications?: boolean;
  };
  isOnline?: boolean;
}

interface UserContextType {
  user: User | null;
  loading: boolean;
  isAuthenticated: boolean;
  error: string | null;
  login: (
    phone: string,
    password: string,
    type: "admin" | "teacher" | "student",
    rememberMe?: boolean
  ) => Promise<any>;
  logout: () => void;
  refreshAuth: () => Promise<void>;
  hasPermission: (permission: string) => boolean;
  getToken: () => string | null;
  getRememberMe: () => boolean;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const useUser = (): UserContextType => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
};

export const UserProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  // 使用新的useAuth Hook
  const auth = useAuth();

  const contextValue: UserContextType = {
    user: auth.user,
    loading: auth.loading,
    isAuthenticated: auth.isAuthenticated,
    error: auth.error,
    login: auth.login,
    logout: auth.logout,
    refreshAuth: auth.refreshAuth,
    hasPermission: auth.hasPermission,
    getToken: auth.getToken,
    getRememberMe: auth.getRememberMe,
  };

  return (
    <UserContext.Provider value={contextValue}>{children}</UserContext.Provider>
  );
};

export default UserContext;
